using UnityEngine;
using System.Collections;

public class GameController : MonoBehaviour
{
    public MouseAction MainCamera;
    public MouseAction SideCamera;

    public DiceController Dice;
    public PlayerControl[] Players;
    public Transform Arrow;
    public Material FichaBoard;

    public enum Event
    {
        NULL,
        Start,
        Side,
        Conner,
        GoalKick,
        OffSide,

        Fault,
        Penalty,

        YellowCard,
        RedCard
    }

	void Start()
    {
        ArrowIniPos = Arrow.transform.position;
        ArrowIniScale = Arrow.transform.localScale;
	}
	
	void Update()
    {
        HandleDice();
        HandlePlayer();
        

        //Requerido para Detectar
        MainCamera.RefreshHit();
        SideCamera.RefreshHit();
	}

    void HandleDice()
    {
        Dice.GiveMousePosition(SideCamera.GetHitPoint());

        if (SideCamera.OnCursorEnter(Dice.transform))
            Dice.AnimPlay();
        if (SideCamera.OnCursorExit(Dice.transform))
            Dice.AnimStop();
    }

    PlayerControl CurrentPlayer = null;
    bool SetDirection = false;
    bool PerformingMov = false;
    float SelectedSpeed = 0;
    void HandlePlayer()
    {
        foreach (PlayerControl player in Players)
        {
            if (!SetDirection && (MainCamera.OnCursorEnter(player.transform) || MainCamera.OnCursorExit(player.transform)))
            {
                player.ChangeFicha(ref FichaBoard);
            }

            if (Input.GetMouseButtonDown(0) && MainCamera.OnCursorStay(player.transform) && Dice.GetDiceNumber() != 0)
            {
                SetDirection = true;
                CurrentPlayer = player;
            }
        }

        if (Dice.GetDiceNumber() != 0)
        {
            if (SetDirection)
            {
                SelectedSpeed = CurrentPlayer.SetDirection(MainCamera.GetHitPoint(), Arrow);

                if (Input.GetMouseButtonUp(0) && MainCamera.OnCursorStay("Campo"))
                {
                    ResetArrow();

                    PerformingMov = true;
                    SetDirection = false;

                    CurrentPlayer.ChangeFicha(ref FichaBoard);
                    CurrentPlayer.CheckFault(true);
                }
            }

            if (PerformingMov)
            {
                PerformingMov = !CurrentPlayer.PerformMovement(Dice.GetDiceNumber(), SelectedSpeed);
                print(CurrentPlayer.CheckFault(false, 3f));
            }
        }
    }

    Vector3 ArrowIniPos;
    Vector3 ArrowIniScale;
    void ResetArrow()
    {
        Arrow.transform.position = ArrowIniPos;
        Arrow.transform.localScale = ArrowIniScale;
    }
}